package com.like.hospitalworld;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.like.dialog.ShareDialogFragment;
import com.like.entity.EventWrapper;
import com.like.entity.GeneralResponse;
import com.like.entity.InfoGetReplyResp;
import com.like.entity.InfoReplyReq;
import com.like.entity.MeetingCourseListReq;
import com.like.entity.MeetingCourseListResp;
import com.like.entity.MeetingDetailReq;
import com.like.entity.MeetingDetailResp;
import com.like.fragment.VideoContentFragment;
import com.like.fragment.VideoReplyFragment;
import com.like.likeutils.device.KeyBoardUtils;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.InfoService;
import com.like.network.MeetingService;
import com.like.network.RetrofitUtil;
import com.like.utils.Constants;
import com.like.widget.MyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

import static com.like.likeutils.device.KeyBoardUtils.closeKeybord;
import static com.like.likeutils.device.KeyBoardUtils.openKeybord;

@ContentView(R.layout.activity_video)
public class VideoActivity extends BaseActivity {

    public static final int REQUEST_PARENT_COMMENT = 100;

    @ViewInject(R.id.comment_real_container)
    private RelativeLayout mCommentRealContainer;
    @ViewInject(R.id.comment_container)
    private FrameLayout mCommentContainer;
    @ViewInject(R.id.edit_comment_real)
    private EditText mEditCommentReal;
    @ViewInject(R.id.edit_comment)
    private EditText mEditComment;

    private VideoContentFragment mContentFragment;
    private VideoReplyFragment mReplyFragment;
    private MeetingService mMeetingService;
    private InfoGetReplyResp.InformationComment mParentComment;
    private InfoService mInfoService;
    private ShareDialogFragment mShareDialog;
    private MeetingDetailResp mMeetingDetail;
    private int mMeetingId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mMeetingId = getIntent().getIntExtra("meetingId", -1);
        mMeetingService = RetrofitUtil.getService(MeetingService.class);
        mShareDialog = new ShareDialogFragment();
        mInfoService = RetrofitUtil.getService(InfoService.class);
        initFragments(mMeetingId);
        getVideoCourse();
        showContent();
        mEditComment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    openComment();
                }
            }
        });
        mEditCommentReal.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    closeComment(false);
                }
            }
        });
    }

    private void openComment() {
        mCommentContainer.setVisibility(View.GONE);
        mCommentRealContainer.setVisibility(View.VISIBLE);
        mEditCommentReal.requestFocus();
        KeyBoardUtils.openKeybord(mEditCommentReal, m.mContext);
    }

    private void closeComment(boolean clearText) {
        KeyBoardUtils.closeKeybord(mEditCommentReal, m.mContext);
        mCommentContainer.setVisibility(View.VISIBLE);
        mCommentRealContainer.setVisibility(View.GONE);
        if (clearText) {
            mEditCommentReal.setText("");
            mEditCommentReal.setHint("回复：");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void getEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, getClass(), REQUEST_PARENT_COMMENT)) {
            this.mParentComment = (InfoGetReplyResp.InformationComment) event.data;
        }
    }

    private void getVideoCourse() {
        MeetingCourseListReq req = new MeetingCourseListReq(1, mMeetingId, 0, 15);
        Call<GeneralResponse<MeetingCourseListResp>> call = mMeetingService.getMeetingCourseList(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<MeetingCourseListResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<MeetingCourseListResp>> call, Response<GeneralResponse<MeetingCourseListResp>> response) {
                MeetingCourseListResp resp = response.body().data;
                List<MeetingCourseListResp.MeetingCourse> courses = resp.meetingInformationList;
                if (courses.size() > 0) {
                    MeetingCourseListResp.MeetingCourse meetingCourse = courses.get(0);
                    getVideoDetail(meetingCourse);
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<MeetingCourseListResp>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void getVideoDetail(MeetingCourseListResp.MeetingCourse course) {
        MeetingDetailReq req = new MeetingDetailReq(course.id, m.getLoginResp().userID);
        Call<GeneralResponse<MeetingDetailResp>> call = mMeetingService.getMeetingDetail(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<MeetingDetailResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<MeetingDetailResp>> call, Response<GeneralResponse<MeetingDetailResp>> response) {
                GeneralResponse<MeetingDetailResp> resp = response.body();
                MeetingDetailResp meetingDetail = resp.data;
                mMeetingDetail = meetingDetail;
                mContentFragment.setMeetingDetail(meetingDetail);
                mReplyFragment.setMeetingDetail(meetingDetail);
            }

            @Override
            public void onFailure(Call<GeneralResponse<MeetingDetailResp>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Event(R.id.replies)
    private void showReplyClick(View v) {
        showReply();
    }

    @Event(R.id.share)
    private void shareClick(View v) {
        mShareDialog.show(getSupportFragmentManager(), "share_dialog");
    }

    @Event(R.id.send_reply)
    private void replyClick(View v) {
        String comment = mEditCommentReal.getText().toString();
        if (TextUtils.isEmpty(comment)) {
            MyToast.showBlueCircleToast(m.mContext, "请输入评论");
            return;
        }
        sendReply(comment);
    }

    private void sendReply(String comment) {
        int subId = 0;
        if (mParentComment != null)
            subId = mParentComment.id;
        InfoReplyReq req = new InfoReplyReq(mMeetingDetail.id, m.getLoginResp().userID, comment, subId);
        Call<GeneralResponse<Object>> call = mInfoService.reply(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<Object>>() {
            @Override
            public void onResponse(Call<GeneralResponse<Object>> call, Response<GeneralResponse<Object>> response) {
                GeneralResponse res = response.body();
                if (res.result == 1) {
                    MyToast.showBlueCircleToast(m.mContext, "评论成功");
                    closeComment(true);
                    mContentFragment.refreshReplyList();
                    mReplyFragment.refreshReply();
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<Object>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void initFragments(int meetingId) {
        mContentFragment = new VideoContentFragment();
        mContentFragment.setMeetingId(meetingId);
        mReplyFragment = new VideoReplyFragment();
    }

    private void showContent() {
        if (mContentFragment.isAdded() || mContentFragment.isVisible())
            return;
        if (mReplyFragment.isAdded() && mReplyFragment.isVisible())
            getSupportFragmentManager().beginTransaction().replace(R.id.content_container, mContentFragment).commit();
        else
            getSupportFragmentManager().beginTransaction().add(R.id.content_container, mContentFragment).commit();
    }

    private void showReply() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mReplyFragment.isAdded() || mReplyFragment.isVisible())
            return;
        if (mContentFragment.isAdded() && mContentFragment.isVisible()) {
            transaction.addToBackStack(null);
            transaction.replace(R.id.content_container, mReplyFragment);
            transaction.commit();
        } else
            getSupportFragmentManager().beginTransaction().add(R.id.content_container, mReplyFragment).commit();
    }

}
